
using Newtonsoft.Json;
using Local.Editor.DataTableTools;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;
namespace Local
{
    public class DateTableSetting
    {
        public string[] m_Tables;
    }
    public class DateTableCodeGeneratorWindow : EditorWindow
    {
        [MenuItem("DataTable/Editor")]
        public static void Create()
        {
            GetWindow<DateTableCodeGeneratorWindow>();
        }
        [SerializeField]
        string[] m_Tables;

        SerializedObject serializedObject;
        SerializedProperty Tables;
        private void OnGUI()
        {
            serializedObject.Update();
            EditorGUI.BeginChangeCheck();
            EditorGUILayout.PropertyField(Tables,new GUIContent("数据表"));

            if(EditorGUI.EndChangeCheck())
            {
                serializedObject.ApplyModifiedProperties();
            }
            if(GUILayout.Button("构建表单代码"))
            {
                Save();
                DataTableGeneratorMenu.GenerateDataTables();
            }
        }
        private void OnEnable()
        {
            serializedObject = new SerializedObject(this);
            Tables = serializedObject.FindProperty("m_Tables");

            //导入setting
            if (File.Exists(Path.Combine("Assets/Local/Configs", "DateTableSetting.json")))
            {
                var setting = JsonConvert.DeserializeObject<DateTableSetting>(File.ReadAllText(Path.Combine("Assets/Local/Configs", "DateTableSetting.json")));
                if (setting != null)
                {
                    m_Tables = setting.m_Tables;
                }
            }
        }
        private void OnDisable()
        {
            Save();
        }
        void Save()
        {
            DateTableSetting dateTableSetting = new DateTableSetting() { m_Tables = m_Tables };
            string json = JsonConvert.SerializeObject(dateTableSetting, Formatting.Indented);
            if (!Directory.Exists("Assets/Local/Configs"))
            {
                Directory.CreateDirectory("Assets/Local/Configs");
            }
            FileStream fileStream = new FileStream(Path.Combine("Assets/Local/Configs", "DateTableSetting.json"), FileMode.OpenOrCreate);
            StreamWriter sw = new StreamWriter(fileStream, Encoding.UTF8);
            sw.WriteLine(json);
            sw.Close();
            fileStream.Close();
        }
    }

}
